package cn.lnexin.collection;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Map;
/**
 * 集合类的高效对比操作
 */
public class CollectionUtil {
	/**
	 * 不允许实例化
	 */
	private CollectionUtil() {}
	
	/**
	 * 获取两个集合的不同元素
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Collection getDiffent(Collection collnew, Collection collold) {
		// 使用LinkeList防止差异过大时,元素拷贝
		Collection result  = new LinkedList();
		Collection max = collnew;
		Collection min = collold;
		// 先比较大小,这样会减少后续map的if判断次数
		if (collnew.size() < collold.size()) {
			max = collold;
			min = collnew;
		}
		// 直接指定大小,防止再散列
		Map<Object, Integer> map = new HashMap<Object, Integer>(max.size());
		for (Object object : max) {
			map.put(object, 1);
		}
		for (Object object : min) {
			if (map.get(object) == null) {
				result.add(object);
			} else {
				map.put(object, 2);
			}
		}
		for (Map.Entry<Object, Integer> entry : map.entrySet()) {
			if (entry.getValue() == 1) {
				result.add(entry.getKey());
			}
		}
		return result;
	}
	
	/**
	 * 获取两个集合的不同元素,去除重复
	 * @return
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Collection getDiffentNoDuplicate(Collection collnew, Collection collold) {
		return new HashSet(getDiffent(collnew, collold));
	}
}
